<template>
<div class="AdministrativeList">
    <el-row class="line">
        <el-col :span="6">
            <!-- :current-node-key="data.administrativeCode" -->
            <el-card>
                <el-tree highlight-current @node-click="handleNodeClick" :current-node-key="data.administrativeCode" :data="data" ref="tagtree" :props="defaultProps" :load="loadNode" lazy>
                </el-tree>
            </el-card>
        </el-col>
        <el-col :span="18">
            <el-card>
                <el-form :inline="false" ref="form" :rules="rules" :model="areaModel" label-width="80px" class="demo-form-inline">
                    <el-form-item label="区域编号" prop="administrativeCode">
                        <el-input v-model="areaModel.administrativeCode" minlength="6" maxlength="12" show-word-limit placeholder="请输入内容"></el-input>
                    </el-form-item>
                    <el-form-item label="区域名称" prop="administrativeName">
                        <el-input v-model="areaModel.administrativeName" minlength="2" maxlength="20" show-word-limit placeholder="请输入内容"></el-input>
                    </el-form-item>

                    <el-form-item label="上级区域" prop="administrativeHighName">
                        <el-input v-model="areaModel.administrativeHighName" minlength="2" maxlength="20" show-word-limit :disabled="true"></el-input>
                        <el-input v-model="areaModel.administrativeHigh" minlength="2" maxlength="20" show-word-limit v-if="false"></el-input>
                    </el-form-item>

                    <el-form-item label="区域等级" prop="administrativeLevel">
                        <el-select :disabled="true" v-model="areaModel.administrativeLevel" style="width: 100%">
                            <el-option label="区级" :value="3"></el-option>
                            <el-option label="镇街级" :value="4"></el-option>
                            <el-option label="村级" :value="5"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button style="float: left" type="primary" :disabled="disableButton01" @click="showOther('form')">新增子分类</el-button>
                        <el-button style="float: left" type="primary" @click="edit('form')">保存</el-button>
                        <el-button style="float: left" type="info" @click="del('form')">删除</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
    </el-row>
</div>
</template>

<script>
import axios from "@/api/request.js";
import {
    convertKey
} from "@/library";
export default {
    name: "AdministrativeList",
    data() {
        return {
            nodeClick: {},
            administrativeHigh: "",
            disableButton01: false,
            modify: 0,
            data: [{
                id: 1,
                label: "佛山市",
                children: [{
                    id: 2,
                    label: "南海区",
                    children: [{
                            id: 3,
                            label: "里水镇2",
                        },
                        {
                            id: 4,
                            label: "桂花街道2",
                        },
                    ],
                }, ],
            }, ],
            defaultProps: {
                children: "children",
                //label: "label",
                label: "administrativeName",
                id: "administrativeCode",
                parentId: "administrativeHigh",
                isLeaf: false,
            },
            isAddOrigan: false,
            addOrganizationForm: {},
            areaModel: {
                administrativeCode: "",
                administrativeName: "",
            },
            tableData2: [],

            OrganizationTree: [],
            search: {
                planName: "",
                planStatus: [{
                        value: 0,
                        label: "全部",
                    },
                    {
                        value: 1,
                        label: "未发布",
                    },
                    {
                        value: 2,
                        label: "已发布",
                    },
                    {
                        value: 3,
                        label: "已撤回",
                    },
                    {
                        value: 4,
                        label: "已启用",
                    },
                    {
                        value: 5,
                        label: "已停用",
                    },
                ],
                value: "",
            },
            params: {
                pageNumber: 1,
                pageSize: 10,
            },
            paging: {},
            tableData: [],
            rules: {
                administrativeCode: [{
                        required: true,
                        message: "行政区域编号不能为空",
                        trigger: "blur",
                    },
                    {
                        min: 6,
                        max: 12,
                        message: "行政区域编号不能为空，长度在 6 到 12 个字符",
                        trigger: "blur",
                    },
                ],
                administrativeName: [{
                        required: true,
                        message: "行政区域名称不能为空",
                        trigger: "blur",
                    },
                    {
                        min: 2,
                        max: 20,
                        message: "行政区域名称不能为空，长度在 2 到 20 个字符",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    computed: {
        treeItem() {
            let administrative;
            if (localStorage.getItem("treeItem")) {
                administrative = JSON.parse(localStorage.getItem("treeItem"));
            } else {
                administrative = this.tableData;
            }
            return administrative;
        },
    },
    created() {
        this.getAdministrativeList();
    },
    mounted() {
        //this.treeLoad();
    },
    methods: {
        loadNode(node, resolve) {
            // 加载 树数据
            let that = this;
            this.nodeClick = node;
            if (node.level === 0) {
                that.loadtreeData(resolve);
            }

            if (node.level >= 1) {
                this.getChildByList(node.data.administrativeCode, resolve);
                return resolve([]); // 加上这个，防止在该节点没有子节点时一直转圈的问题发生。
            }
        },
        loadtreeData() {
            axios
                .get(`baseinfo/v1.0/adminstrative/getByPid`, {
                    params: {
                        pid: 440600,
                    },
                })
                .then((res) => {
                    let data = res.data;
                    this.data = res.data;

                    // 前者item.参数名称为 prop中的规定的属性名称
                    data.forEach((item) => {
                        if (item.administrativeCode.length >= 12) {
                            delete item.children
                        }
                        item.administrativeCode = item.administrativeCode;
                        item.administrativeHigh = item.administrativeHigh;
                        item.administrativeName = item.administrativeName;
                        item.isLeaf = true;
                    });
                    resolve(data)
                });
        },

        getChildByList(pid, resolve) {
            // 获取子节点请求
            let params = {
                pid: pid,
            };
            axios
                .get(`baseinfo/v1.0/adminstrative/getByPid`, {
                    params: params,
                })
                .then((res) => {
                    let data = res.data;

                    // 前者item.参数名称为 prop中的规定的属性名称
                    data.forEach((item) => {
                        if (item.administrativeCode.length >= 12) {
                            delete item.children
                        }
                        item.administrativeCode = item.administrativeCode;
                        item.administrativeHigh = item.administrativeHigh;
                        item.administrativeName = item.administrativeName;
                        item.isLeaf = true;
                    });
                    resolve(data)
                });
        },
        treeLoad() {
            let url = "/tree.json";
            fetch(url)
                .then((response) => response.json())
                .then((res) => {
                    this.data = res.data.treeItem;
                    this.data = convertKey(this.data, {
                        administrativeName: "label",
                        administrativeCode: "id",
                    });
                });
        },
        handleNodeClick(data, e) {
            console.log(data);
            console.log(e.parent.data);

            //this.nodeClick=e;
            this.areaModel.id = data.id;
            this.areaModel.administrativeCode = data.administrativeCode;
            this.areaModel.administrativeName = data.administrativeName;
            this.areaModel.administrativeHigh = data.administrativeHigh;
            this.areaModel.administrativeHighName = e.parent.data.administrativeName;
            this.areaModel.administrativeLevel = data.administrativeLevel;
            //是否能创建子区域 3、4可以 5不可以
            if (this.areaModel.administrativeLevel == 5) {
                this.disableButton01 = true;
            } else {
                this.disableButton01 = false;
            }

            //修改状态
            this.modify = 1;
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },

        statusChange(item) {
            console.log(item);
        },
        planStatusCn(index) {
            var planStatus = {
                1: "未发布",
                2: "已发布",
                3: "已撤回",
                4: "已启用",
                5: "已停用",
            };

            return planStatus[index];
        },
        load(tree, treeNode, resolve) {
            setTimeout(() => {
                resolve([{
                        id: 31,
                        date: "2016-05-01",
                        name: "王小虎",
                        address: "上海市普陀区金沙江路 1519 弄",
                    },
                    {
                        id: 32,
                        date: "2016-05-01",
                        name: "王小虎",
                        address: "上海市普陀区金沙江路 1519 弄",
                    },
                ]);
            }, 1000);
        },
        onSearch() {},
        handleSizeChange(pageSize) {
            this.params.pageSize = pageSize;
            this.getAdministrativeList(this.params.pageNumber, this.params.pageSize);
        },
        currentchange(pageNumber) {
            this.params.pageNumber = pageNumber;
            this.getAdministrativeList(this.params.pageNumber, this.params.pageSize);
        },
        getAdministrativeList(pageNumber = 1, pageSize = 10) {
            this.$common.getAdministrativeList(pageNumber, pageSize).then((res) => {
                this.tableData = res.data.treeItem;
                localStorage.setItem("treeItem", JSON.stringify(this.tableData));
            });
        },
        showOther() {
            //新增状态
            this.modify = 0;
            this.areaModel.administrativeHigh = this.areaModel.administrativeCode;
            this.areaModel.administrativeHighName = this.areaModel.administrativeName;
            this.areaModel.administrativeLevel =
                this.areaModel.administrativeLevel + 1;
            this.areaModel.administrativeCode = "";
            this.areaModel.administrativeName = "";
        },
        edit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let jsonData = {
                        administrativeCode: this.areaModel.administrativeCode,
                        administrativeName: this.areaModel.administrativeName,
                        administrativeHigh: this.areaModel.administrativeHigh,
                        administrativeLevel: this.areaModel.administrativeLevel,
                    };
                    //新增或修改 新节点
                    if (this.modify == 0) {
                        //新增
                        axios
                            .post(`baseinfo/v1.0/adminstrative/add`, {
                                params: jsonData,
                            })
                            .then((response) => {
                                console.log(response);
                                this.$message.success(response.errorMsg);
                                this.areaModel.administrativeCode = "";
                                this.areaModel.administrativeName = "";
                                //局部更新
                                this.refreshNodeBy(this.nodeClick.parent);
                            });
                    } else {
                        jsonData.id = this.areaModel.id;
                        //修改
                        axios
                            .post(`baseinfo/v1.0/adminstrative/put`, {
                                params: jsonData,
                            })
                            .then((response) => {
                                console.log(response);
                                //该行政编码已经存在
                                if (response.errorCode == "00000") {
                                    this.$message.success("操作完成");
                                } else {
                                    this.$message.success("该行政编码已经存在");
                                }

                                //局部更新
                                this.refreshNodeBy(this.nodeClick.parent);
                            });
                    }
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        refreshNodeBy(id) {
            let node = this.$refs.tagtree.getNode(id); // 通过节点id找到对应树节点对象
            //
            node.loaded = false;
            node.expand(); // 主动调用展开节点方法，重新查询该节点下的所有子节点
        },
        del() {
            //选中后，删除节点
            this.$confirm("是否删除?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(() => {
                    axios
                        .post(`baseinfo/v1.0/adminstrative/delete`, {
                            params: {
                                id: this.areaModel.id,
                            },
                        })
                        .then((response) => {
                            console.log(response);
                            if (response.errorCode === "00000") {
                                this.$message.success("删除成功");
                                this.areaModel.administrativeCode = "";
                                this.areaModel.administrativeName = "";
                                //局部更新
                                this.refreshNodeBy(this.nodeClick.parent);
                            } else {
                                this.$message.error(response.errorMsg);
                            }
                        });
                })
                .catch(() => {});
        },
    },
};
</script>

<style lang="scss">
.AdministrativeList {
    .form {
        padding: 15px 10px;
    }

    .el-card {
        width: 98%;
        margin: 0 auto;

        .bottom {
            display: flex;
            justify-content: flex-end;
            margin-top: 15px;
        }
    }

    .line {
        margin-top: 15px;
    }
}
</style>
